import { Component, Input, OnInit } from '@angular/core';
import { AbstractControl } from '@angular/forms';
import { FormDefaultComponent } from './FormDefault.component';
import { FormOptions } from '../models/forms.model';

@Component({
    selector: 'app-form-select',
    templateUrl: './FormSelect.component.html',
})
export class FormSelectComponent extends FormDefaultComponent implements OnInit {
    @Input() set options(options: FormOptions[]) {
        this.configuration.options = options;
    }

    constructor() {
        super();
    }

    ngOnInit() {
        const { formGroupReference, formControlId, options } = this.configuration;
        if (!options) return;
        if (this.configuration.required) {
            const abstractControl: AbstractControl = formGroupReference.get(formControlId);
            const currentValue = abstractControl.value;
            if (!currentValue && options.length > 0) {
                abstractControl.patchValue(options[0].key);
            }
        }
    }

    get applyFakePlaceholderClass() {
        const { formGroupReference, formControlId } = this.configuration;
        return formGroupReference.get(formControlId).value === '';
    }
}
